import axios from "axios";
import store from "@/store";
import { getToken } from "@/utils/auth";
import { MessageBox, Message } from "element-ui";

// create an axios instance
const service = axios.create({
  baseURL: "/",
  withCredentials: true,
  timeout: 50000
});

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers["Authorization"] = "Bearer " + getToken();
    }
    return config;
  },
  error => {
    // do something with request error
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.code === 1) {
      return res;
    } else if (res.code === 100) {
      const msg = res.message || "Error";
      showWarning(msg);
      return Promise.reject(new Error(msg));
    } else {
      const msg = res.message || "Error";
      showError(msg);
      return Promise.reject(new Error(msg));
    }
  },
  error => {
    errorHandle(error);
    return Promise.reject(error);
  }
);

/**
 * 错误处理
 */
function errorHandle(error) {
  console.log("----3----");
  console.log(error);
  let that = this;
  let msg = error.message;
  const { response } = error;
  if (response) {
    const { data } = response;
    if (data) {
      msg = data.Message;
    } else {
      switch (response.status) {
        // 提交的参数有问题
        case 400:
          msg = "提交参数有误";
          break;
        case 401:
          console.log("---4-------");
          msg = "登录过期, 请重新登录";
          store.dispatch("user/logout").then(() => {
            location.reload();
          });
          break;
        case 403:
          msg = "您没有访问权限";
          break;
        default:
          msg = "系统错误";
          break;
      }
    }
  }
  showError(msg);
}

/**
 * 显示警告消息
 * @param {警告消息} msg
 */
function showWarning(msg) {
  Message({
    message: msg,
    type: "warning",
    duration: 5 * 1000
  });
}

/**
 * 显示错误消息
 * @param {错误消息} msg
 */
function showError(msg) {
  Message({
    message: msg,
    type: "error",
    duration: 5 * 1000
  });
}

export default service;
